package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;

import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;

import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.entity.PageBean;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    // 员工--持久层
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("加密结果：{}", password);

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


    /**
     * 添加员工
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {


        // 转换
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        log.info("Employee 数据为：{}", employee.toString());



        // 默认 密码
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(password);

        // 账户状态 ，默认为 1 （1 启用，0 禁用）
        employee.setStatus(StatusConstant.ENABLE);




        log.info("数据补全：{}", employee.toString());

        // 调用持久层
        employeeMapper.insert(employee);


    }

    /**
     * 员工分页查询
     */
    @Override
    public PageBean page(String name, Integer page, Integer pageSize) {

        // 设置分页数据
        PageHelper.startPage(page, pageSize);

        // 调用持久层--》条件查询
        List<Employee> employees = employeeMapper.page(name);

        // 分页结果
        Page<Employee> p = (Page<Employee>) employees;

        return new PageBean(p.getTotal(), p.getResult());

    }

    /**
     * 启用、禁用员工账号
     */
    @Override
    public void EnableDisableEmployee(Integer status, Long id) {

        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        log.info("---> {}",employee);

        // 调用持久层--》启用、禁用员工账号
        employeeMapper.EnableDisableEmployee(employee);
    }

    /**
     * 根据id查询员工
     */
    @Override
    public EmployeeDTO idEmployee(Integer id) {

        // 调用持久层--》 根据id查询员工
        EmployeeDTO e = employeeMapper.idEmployee(id);

        return e;
    }

    /**
     * 编辑员工信息
     */
    @Override
    public void EditorialStaff(EmployeeDTO employeeDTO) {

        // 拷贝
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        // 调用持久层--》编辑员工信息
        employeeMapper.EditorialStaff(employee);
    }

    /**
     * 员工修改密码
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {


        String stringID = passwordEditDTO.getEmpId().toString();

        // 修改密码，查询当前密码
        Employee employee = employeeMapper.idEmployeePassword(stringID);

        // 旧密码，加密（用于，判断原密码是否正确）
        // 判断原密码是否正确
        String OldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        if (!employee.getPassword().equals(OldPassword)) {
            throw new PasswordEditFailedException("密码修改失败!");
        }

        // 密码加密
        String password = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());

        // 赋值到 employee 类上，（被修改的员工）
        employee.setPassword(password);
        log.info("员工数据：{}", employee);


        // 调用持久层--》员工修改密码
        employeeMapper.editPassword(employee);

    }

}
